package com.itheima.controller.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @version 1.0
 * @date 2021/5/29 21:48
 */
public class AliyunOSSUtil {
    private static final String accessKeyId = OssConstant.OSS_ACCESS_KEY_ID_IM;
    private static final String accessKeySecret = OssConstant.OSS_ACCESS_KEY_SECRET_IM;
    private static final String endpoint = OssConstant.OSS_END_POINT_IM;
    private static final String bucket = OssConstant.OSS_BUCKET_IM;
    private static final String dir = OssConstant.OSS_ACCESS_DIR_PREFIX_IM;

    private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    public static final String URL = "https://mall-ossone.";
    public static String OSSUploadFile(MultipartFile photoFile) throws IOException {
        String fileName = photoFile.getOriginalFilename();
        InputStream inputStream = photoFile.getInputStream();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        if (null == inputStream) {
            return null;
        }
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //容器不存在，就创建
            if (!ossClient.doesBucketExist(bucket)) {
                ossClient.createBucket(bucket);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
                createBucketRequest.setCannedACL(CannedAccessControlList.Default);
                ossClient.createBucket(createBucketRequest);
            }

            String fileUrl = endpoint + "/" +  fileName;


            //上传文件
            PutObjectRequest objectRequest = new PutObjectRequest(bucket, fileName, inputStream);
            ossClient.putObject(objectRequest);

            //设置权限 这里是私有权限读写
            ossClient.setBucketAcl(bucket, CannedAccessControlList.PublicRead);
                logger.info("==========>OSS文件上传成功,OSS地址：" + fileUrl);
                return URL + fileUrl;

        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }
}

